package edu.upc.fib.lamsandroid.client.activity;

import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TabHost;
import com.octo.android.robospice.SpiceManager;
import com.octo.android.robospice.UncachedSpiceService;
import com.octo.android.robospice.persistence.exception.SpiceException;
import com.octo.android.robospice.request.listener.RequestListener;
import edu.upc.fib.lamsandroid.client.R;
import edu.upc.fib.lamsandroid.client.dialog.MessageBoxDialog;
import edu.upc.fib.lamsandroid.client.fragment.LessonSummary;
import edu.upc.fib.lamsandroid.client.request.lesson.GetByOrganisationRequest;
import edu.upc.fib.lamsandroid.client.request.user.OrganisationsRequest;
import edu.upc.fib.lamsandroid.server.api.model.Lesson;
import edu.upc.fib.lamsandroid.server.api.model.Organisation;
import edu.upc.fib.lamsandroid.server.api.response.Response;
import edu.upc.fib.lamsandroid.server.api.response.lesson.GetByOrganisationsResponse;
import edu.upc.fib.lamsandroid.server.api.response.user.OrganisationsResponse;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

public class LessonListActivity extends AbstractBaseActivity/* implements ExpandableListView.OnChildClickListener*/ {
    private SpiceManager spiceManager = new SpiceManager(UncachedSpiceService.class);

    //private LessonExpandableListAdapter lessonsAdapter;

    private Hashtable<Organisation, List<Lesson>> lessonsByOrganisation;
    private int organisationsTotal;
    private int organisationsFetched;

    @Override
    public void onStart() {
        spiceManager.start(this);
        super.onStart();
    }

    @Override
    public void onStop() {
        spiceManager.shouldStop();
        super.onStop();
    }

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);

        setContentView(R.layout.lesson_list);

        //new MessageBoxDialog(this).show("Welcome to LAMS ANDROID PFC SERVER :-)");


        Fragment fragment = new LessonSummary();
        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.contentFragment, fragment);
        transaction.commit();

        lessonsByOrganisation = new Hashtable<Organisation, List<Lesson>>();
        organisationsFetched = 0;
        fetchOrganisations();
    }


    private void renderLessons() {
        /*
        ExpandableListView epView = (ExpandableListView) findViewById(R.id.expandableListView);
        lessonsAdapter = new LessonExpandableListAdapter(this, lessonsByOrganisation);
        epView.setAdapter(lessonsAdapter);
        epView.setOnChildClickListener(this);
        */

        TabHost tabHost = (TabHost) findViewById(R.id.tabHostOrganisations);
        tabHost.setup();

        Enumeration<Organisation> keys = lessonsByOrganisation.keys();
        while(keys.hasMoreElements()) {
            final Organisation organisation = keys.nextElement();

            final LinearLayout linearLayout = new LinearLayout(this);
            linearLayout.setOrientation(LinearLayout.VERTICAL);
            List<Lesson> lessons = lessonsByOrganisation.get(organisation);

            if(lessons.size() > 0) {
                for (Lesson lesson : lessons) {
                    linearLayout.addView(createLessonButton(lesson));
                }

                tabHost.addTab(tabHost.newTabSpec(organisation.getName())
                        .setIndicator(organisation.getName())
                        .setContent(new TabHost.TabContentFactory() {
                            @Override
                            public View createTabContent(String tag) {
                                if (tag.equals(organisation.getName())) {
                                    return linearLayout;
                                }
                                return null;
                            }
                        }));
            }
        }
    }

    private void fetchOrganisations() {
        setProgressBarIndeterminateVisibility(true);

        OrganisationsRequest organisationsRequest = new OrganisationsRequest();
        spiceManager.execute(organisationsRequest, new RequestListener<OrganisationsResponse>() {
            @Override
            public void onRequestFailure(SpiceException e) {
                setProgressBarIndeterminateVisibility(false);
                new MessageBoxDialog(LessonListActivity.this).show(e.toString());
            }

            @Override
            public void onRequestSuccess(OrganisationsResponse organisationsResponse) {
                setProgressBarIndeterminateVisibility(false);
                switch (organisationsResponse.getCode()) {
                    case Response.OPERATION_SUCCESSFUL:
                        List<Organisation> organisations = organisationsResponse.getPayload();
                        organisationsTotal = organisations.size();
                        for (Organisation organisation : organisations) {
                            fetchLessons(organisation);
                        }
                        break;
                    case Response.INVALID_SESSION_STATE:
                        new MessageBoxDialog(LessonListActivity.this).show("Session expired.");
                        finish();
                        //TODO: notify MainActivity that we are logged out
                        break;
                }
            }
        });
    }

    private void fetchLessons(final Organisation organisation) {
        setProgressBarIndeterminateVisibility(true);

        GetByOrganisationRequest getByOrganisationRequest = new GetByOrganisationRequest(organisation.getExternalId());
        spiceManager.execute(getByOrganisationRequest, new RequestListener<GetByOrganisationsResponse>() {
            @Override
            public void onRequestFailure(SpiceException e) {
                setProgressBarIndeterminateVisibility(false);
                new MessageBoxDialog(LessonListActivity.this).show(e.toString());
            }

            @Override
            public void onRequestSuccess(GetByOrganisationsResponse getByOrganisationsResponse) {
                setProgressBarIndeterminateVisibility(false);
                switch (getByOrganisationsResponse.getCode()) {
                    case Response.OPERATION_SUCCESSFUL:
                        lessonsByOrganisation.put(organisation, getByOrganisationsResponse.getPayload());

                        if (++organisationsFetched == organisationsTotal) {
                            renderLessons();
                        }

                        break;
                    case Response.INVALID_SESSION_STATE:
                        new MessageBoxDialog(LessonListActivity.this).show("Session expired.");
                        finish();
                        //TODO: notify MainActivity that we are logged out
                        break;
                }
            }
        });
    }

    private Button createLessonButton(final Lesson lesson) {
        Button button = new Button(getApplicationContext());
        button.setTextSize(12);
        button.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 30));
        button.setText(lesson.getTitle());
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Fragment fragment = new LessonSummary(lesson);
                FragmentManager fm = getFragmentManager();
                FragmentTransaction transaction = fm.beginTransaction();
                transaction.replace(R.id.contentFragment, fragment);
                transaction.commit();
            }
        });

        return button;
    }

    /*
    @Override
    public boolean onChildClick(ExpandableListView expandableListView, View view, int groupPosition, int childPosition,
                                long id) {

        Lesson lesson = (Lesson) lessonsAdapter.getChild(groupPosition, childPosition);
        LamsAndroidClientApplication.getInstance().setCurrentLesson(lesson);

        startActivity(new Intent(LessonListActivity.this, LessonActivity.class));

        return true;
    }
    */

}